package com.study.zrouter;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import dalvik.system.DexFile;

/**
 * 路由
 */
public class ZRouter {
    private static final ZRouter zRouter = new ZRouter();
    //路由注册表
    private static final Map<String, String> routeMap = new HashMap<>();

    private ZRouter() {
    }

    public static ZRouter instance() {
        return zRouter;
    }

    private static boolean isRegisterByPlugin = false;

    /**
     * 需要插装的方法
     */
    private void registerByPlugin() {

    }

    /**
     * 注册
     */
    private static void register(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            if (IRouter.class.isAssignableFrom(clazz)) {
                IRouter iRouter = (IRouter) clazz.newInstance();
                iRouter.register(routeMap);
                isRegisterByPlugin = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化
     */
    public void init(@NonNull Application context) {
        registerByPlugin();

        if (isRegisterByPlugin) {
            return;
        }

        try {
            //获取安装的apk文件
            String path = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
            Log.d("获取apk路径", path);
            //获取到项目中所有的类信息描述，遍历找到路由注册表
            DexFile dexFile = new DexFile(path);
            Enumeration<String> enumeration = dexFile.entries();
            //每次启动APP需要遍历所有的类信息，损耗性能
            while (enumeration.hasMoreElements()) {
                String className = enumeration.nextElement();
                if (className.contains("com.z_router.map")) {
                    Log.e("路由注册类", className);

                    Class<?> clazz = Class.forName(className);
                    //判断是否为IRouter的子类
                    if (IRouter.class.isAssignableFrom(clazz)) {
                        IRouter iRouter = (IRouter) clazz.newInstance();
                        //向路由表注册路由
                        iRouter.register(routeMap);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 路由
     *
     * @param activity 当前activity
     * @param key      要跳转的路由表的key
     * @param bundle   入参（可为空）
     */
    public void routeTo(@NonNull Activity activity, @NonNull String key, @Nullable Bundle bundle) {
        if (routeMap.containsKey(key) && routeMap.get(key) != null) {
            try {
                Intent intent = new Intent(activity, Class.forName(Objects.requireNonNull(routeMap.get(key))));
                if (bundle != null) {
                    intent.putExtras(bundle);
                }
                activity.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
